package com.uduemc.biso.node.web.component.html;

import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.util.HtmlUtils;

import com.uduemc.biso.node.core.common.sysconfig.PdtableSysConfig;
import com.uduemc.biso.node.core.common.sysconfig.pdtablesysconfig.PdtableSysItemConfig;
import com.uduemc.biso.node.core.common.sysconfig.pdtablesysconfig.PdtableSysListConfig;
import com.uduemc.biso.node.core.common.sysconfig.pdtablesysconfig.PdtableSysListTextConfig;
import com.uduemc.biso.node.core.common.udinpojo.PagingData;
import com.uduemc.biso.node.core.entities.HRepertory;
import com.uduemc.biso.node.core.entities.SCategories;
import com.uduemc.biso.node.core.entities.SPage;
import com.uduemc.biso.node.core.entities.SPdtable;
import com.uduemc.biso.node.core.entities.SPdtableItem;
import com.uduemc.biso.node.core.entities.SPdtableTitle;
import com.uduemc.biso.node.core.entities.SSystem;
import com.uduemc.biso.node.core.entities.SSystemItemCustomLink;
import com.uduemc.biso.node.core.entities.custom.CategoryQuote;
import com.uduemc.biso.node.core.entities.custom.PdtableList;
import com.uduemc.biso.node.core.entities.custom.RepertoryQuote;
import com.uduemc.biso.node.core.entities.custom.pdtable.PdtableItem;
import com.uduemc.biso.node.core.entities.custom.pdtable.PdtableTitleCategoryConf;
import com.uduemc.biso.node.core.entities.custom.pdtable.PdtableTitleFileConf;
import com.uduemc.biso.node.core.entities.custom.pdtable.PdtableTitleImageConf;
import com.uduemc.biso.node.core.utils.PdtableTitleConfigUtil;
import com.uduemc.biso.node.core.utils.SystemConfigUtil;
import com.uduemc.biso.node.web.component.SiteUrlComponent;
import com.uduemc.biso.node.web.component.SpringContextUtils;
import com.uduemc.biso.node.web.component.html.common.HCPagingUdin;
import com.uduemc.biso.node.web.component.html.common.SystemListCrumbs;
import com.uduemc.biso.node.web.component.html.common.SystemListSearch;
import com.uduemc.biso.node.web.service.byfeign.SystemService;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Filter;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;

@Component
public class HSystemPdtableItemListUdin {

	private static String name = "system_pdtable_item_list";

	@Autowired
	private BasicUdin basicUdin;

	@Autowired
	private SiteUrlComponent siteUrlComponent;

	@Autowired
	private SystemListCrumbs systemListCrumbs;

	@Autowired
	private SystemListSearch systemListSearch;

	@Autowired
	private HCPagingUdin hCPagingUdin;

	public StringBuilder html(SSystem system, SPage page, PdtableList pdtableList, SCategories sCategories, List<SCategories> listSCategories, String keyword,
			int pageNum) throws IOException {
		if (system == null || page == null || pdtableList == null) {
			return new StringBuilder("<!-- PLComp empty pdtableSystem -->\n");
		}
		// 获取系统配置
		PdtableSysConfig pdtableSysConfig = SystemConfigUtil.pdtableSysConfig(system);
		PdtableSysListConfig list = pdtableSysConfig.getList();
		PdtableSysListTextConfig ltext = pdtableSysConfig.getLtext();
		// 通过系统id 制作唯一编码
		String md5Id = SecureUtil.md5(String.valueOf(page.getId()));
		// 文本没有数据
		String noData = HtmlUtils.htmlEscape(ltext.getNoData());
		// 每页数据量
		int perpage = list.getPerpage();
		int tablestyle = list.getTablestyle();
		String pagewidth = list.getPagewidth();

		// 顶部class
		String topClass = getTopClass(list);

		// 制作面包屑
		// crumbs
		List<SCategories> crumbsSCategoriesList = new ArrayList<>();
		idList(crumbsSCategoriesList, listSCategories, sCategories != null ? sCategories.getId() : null);
		// 反转链表
		CollUtil.reverse(crumbsSCategoriesList);
		String crumbs = crumbs(pdtableSysConfig, page, crumbsSCategoriesList);

		// 搜索
		// search
		StringBuilder search = search(pdtableSysConfig, keyword, md5Id);

		// 生成html渲染内容
		StringBuilder stringBuilder = new StringBuilder("<!-- PdtableLComp -->\n");

		Map<String, Object> mapData = new HashMap<>();
		mapData.put("topClass", topClass);
		mapData.put("crumbs", crumbs);
		mapData.put("search", search);

		List<SPdtableTitle> listSPdtableTitle = pdtableList.getTitle();
		// 过滤 listSPdtableTitle 数据，status 不显示的不要
		CollUtil.filter(listSPdtableTitle, new Filter<SPdtableTitle>() {
			@Override
			public boolean accept(SPdtableTitle filterSPdtableTitle) {
				Short status = filterSPdtableTitle.getStatus();
				return status == null || status.shortValue() != (short) 1 ? false : true;
			}
		});

		List<PdtableItem> rows = pdtableList.getRows();
		long total = pdtableList.getTotal();
		if (total < 1) {
			// 显示没有数据
			mapData.put("noData", noData);
			stringBuilder.append(basicUdin.render(name, "nodata", mapData));
			return stringBuilder;
		}
		if (CollUtil.isEmpty(listSPdtableTitle)) {
			// 显示没有属性
			mapData.put("noData", noData);
			stringBuilder.append(basicUdin.render(name, "nodata", mapData));
			return stringBuilder;
		} else {
			boolean sPdtableTitleStatusShow = false;
			for (SPdtableTitle sPdtableTitle : listSPdtableTitle) {
				Short status = sPdtableTitle.getStatus();
				if (status != null && status.shortValue() == 1) {
					sPdtableTitleStatusShow = true;
				}
			}
			if (sPdtableTitleStatusShow == false) {
				// 显示没有属性
				mapData.put("noData", noData);
				stringBuilder.append(basicUdin.render(name, "nodata", mapData));
				return stringBuilder;
			}
		}

		String tableTheadTrThHtml = tableTheadTrThHtml(listSPdtableTitle);
		String tableTbodyTrHtml = tableTbodyTrHtml(page, sCategories, listSPdtableTitle, rows, pdtableSysConfig);
		// 分页部分
		String listHref = siteUrlComponent.getListHref(page, sCategories, "[page]", "");
		PagingData pagingData = ltext.getPagingData();
		int pageTotal = (int) Math.ceil((double) total / (double) perpage);
		// pagging
		StringBuilder pagging = hCPagingUdin.html(listHref, pageNum, pageTotal, pagingData);

		String pagewidthScript = pagewidthScript(pagewidth);

		mapData.put("tableTheadTrThHtml", tableTheadTrThHtml);
		mapData.put("tableTbodyTrHtml", tableTbodyTrHtml);
		mapData.put("pagging", pagging.toString());
		mapData.put("pagewidthScript", pagewidthScript);
		StringWriter render = basicUdin.render(name, "default_" + tablestyle, mapData);
		stringBuilder.append(render);

		return stringBuilder;
	}

	protected StringBuilder pdtableSystemItemHtml(SPage sPage, SCategories sCategories, SPdtableTitle sPdtableTitle, PdtableItem pdtableItem,
			PdtableSysConfig pdtableSysConfig) {
		PdtableSysItemConfig pdtableSysItemConfig = pdtableSysConfig.getItem();
		int itemshow = pdtableSysItemConfig.getItemshow();

		List<SPdtableItem> listItem = pdtableItem.getListItem();
		RepertoryQuote image = pdtableItem.getImage();
		RepertoryQuote file = pdtableItem.getFile();
		List<CategoryQuote> listCategoryQuote = pdtableItem.getListCategoryQuote();

		StringBuilder stringBuilder = new StringBuilder();
		Short type = sPdtableTitle.getType();
		if (type == null) {
			stringBuilder.append("<td></td>");
		}

		if (type.shortValue() == (short) 1) {
			Optional<SPdtableItem> findFirst = listItem.stream().filter(item -> {
				return item.getPdtableTitleId().longValue() == sPdtableTitle.getId().longValue();
			}).findFirst();
			if (findFirst.isPresent()) {
				SPdtableItem sPdtableItem = findFirst.get();
				String value = StrUtil.trim(sPdtableItem.getValue());
				value = StrUtil.isNotBlank(value) ? HtmlUtils.htmlEscape(value) : value;
				if (StrUtil.isBlank(value)) {
					stringBuilder.append("<td><!-- value is blank --></td>");
				} else {
					// 是否显示详情页面，如果是则加入详情链接的a标签
					if (itemshow == 1) {
						SPdtable sPdtable = pdtableItem.getData();
						SystemService systemServiceImpl = SpringContextUtils.getBean("systemServiceImpl", SystemService.class);
						SSystemItemCustomLink sSystemItemCustomLink = null;
						try {
							sSystemItemCustomLink = systemServiceImpl.findOkOneByHostSiteSystemItemId(sPdtable.getHostId(), sPdtable.getSiteId(),
									sPdtable.getSystemId(), sPdtable.getId());
						} catch (IOException e) {
						}
						String href = siteUrlComponent.getPdtableHref(sPage, sCategories, sPdtable, sSystemItemCustomLink);
						value = "<a href=\"" + href + "\" >" + value + "</a>";
					}
					stringBuilder.append("<td>" + value + "</td>");
				}
			} else {
				stringBuilder.append("<td><!-- no value --></td>");
			}
		} else if (type.shortValue() == (short) 2) {
			if (image == null || image.getHRepertory() == null) {
				stringBuilder.append("<td><!-- no image --></td>");
			} else {
				HRepertory hRepertory = image.getHRepertory();
				String imgSrc = siteUrlComponent.getImgSrc(hRepertory);
				String hRepertoryMdId = SecureUtil.md5(String.valueOf(hRepertory.getId()));
				PdtableTitleImageConf imageConf = PdtableTitleConfigUtil.imageConf(sPdtableTitle);
				String tdText = imageConf.getTdText();
				tdText = StrUtil.isNotBlank(tdText) ? HtmlUtils.htmlEscape(tdText) : tdText;

				String aImgTag = "<a style=\"cursor:pointer;\" data-alt=\"\" class=\"fancybox-thumbs\" href=\"" + imgSrc + "\" data-lightbox=\"image-"
						+ hRepertoryMdId + "\">" + tdText + "</a>";

				stringBuilder.append("<td>" + aImgTag + "</td>");
			}
		} else if (type.shortValue() == (short) 3) {
			if (file == null || file.getHRepertory() == null) {
				stringBuilder.append("<td><!-- no file --></td>");
			} else {
				HRepertory hRepertory = file.getHRepertory();
				String downloadHref = siteUrlComponent.getDownloadHref(hRepertory.getId());
				PdtableTitleFileConf fileConf = PdtableTitleConfigUtil.fileConf(sPdtableTitle);
				int fileConfType = fileConf.getType();
				String tdText = fileConf.getTdText();
				String obText = fileConf.getObText();

				tdText = StrUtil.isNotBlank(tdText) ? HtmlUtils.htmlEscape(tdText) : "";
				obText = StrUtil.isNotBlank(obText) ? HtmlUtils.htmlEscape(obText) : "";

				String suffix = hRepertory.getSuffix();
				String iconClass = HSystemDownloadItemListUdin.getIconClassMap(suffix);

				String iHtml = "";
				if (fileConfType == 1) {
					iHtml = "<i class=\"" + iconClass + "\"></i>";
				} else {
					iHtml = tdText;
				}

				String aDownloadTag = "";
				if (suffix.toLowerCase().equals("pdf")) {
					String onlineBrowseHref = siteUrlComponent.getPreviewPdfHref(hRepertory.getOriginalFilename(), hRepertory.getId());
					if (fileConfType == 1) {
						aDownloadTag += "<a style=\"cursor:pointer;\" target=\"_blank\" class=\"fancybox-thumbs\" href=\"" + onlineBrowseHref
								+ "\" ><img style=\"width: 25px;height: 25px;\" src=\"/assets/static/site/np_template/images/icon_preview1.png\" /></a>&nbsp;&nbsp;";
					} else {
						aDownloadTag += "<a style=\"cursor:pointer;\" target=\"_blank\" class=\"fancybox-thumbs\" href=\"" + onlineBrowseHref + "\" >" + obText
								+ "</a>&nbsp;&nbsp;";
					}
				}

				aDownloadTag += "<a style=\"cursor:pointer;\" target=\"_blank\" class=\"fancybox-thumbs\" href=\"" + downloadHref + "\" >" + iHtml + "</a>";
				stringBuilder.append("<td>" + aDownloadTag + "</td>");
			}
		} else if (type.shortValue() == (short) 4) {
			if (CollUtil.isEmpty(listCategoryQuote)) {
				stringBuilder.append("<td><!-- no category --></td>");
			} else {
				PdtableTitleCategoryConf categoryConf = PdtableTitleConfigUtil.categoryConf(sPdtableTitle);
				String separator = categoryConf.getSeparator();
				int linkshow = categoryConf.getLinkshow();
				String categoryTdHtml = "";
				for (CategoryQuote categoryQuote : listCategoryQuote) {
					if (categoryQuote != null) {
						SCategories sCategoriesItem = categoryQuote.getSCategories();
						if (sCategoriesItem != null) {
							String sCategoriesName = sCategoriesItem.getName();
							if (StrUtil.isNotBlank(sCategoriesName)) {
								String categoryHtml = "";
								if (linkshow == 1) {
									String categoryHref = siteUrlComponent.getCategoryHref(sPage, sCategoriesItem);
									categoryHtml = "<a href=\"" + categoryHref + "\">" + sCategoriesName + "</a>";
								} else {
									categoryHtml = sCategoriesName;
								}

								if (StrUtil.isBlank(categoryTdHtml)) {
									categoryTdHtml = categoryHtml;
								} else {
									categoryTdHtml += separator + categoryHtml;
								}
							}
						}
					}
				}
				stringBuilder.append("<td>" + categoryTdHtml + "</td>");
			}
		} else if (type.shortValue() == (short) 5) {
			Optional<SPdtableItem> findFirst = listItem.stream().filter(item -> {
				return item.getPdtableTitleId().longValue() == sPdtableTitle.getId().longValue();
			}).findFirst();
			if (findFirst.isPresent()) {
				SPdtableItem sPdtableItem = findFirst.get();
				String value = StrUtil.trim(sPdtableItem.getValue());
				value = StrUtil.isNotBlank(value) ? HtmlUtils.htmlEscape(value) : value;
				if (StrUtil.isBlank(value)) {
					stringBuilder.append("<td><!-- value is blank --></td>");
				} else {
					// 是否显示详情页面，如果是则加入详情链接的a标签
					if (itemshow == 1) {
						SPdtable sPdtable = pdtableItem.getData();
						SystemService systemServiceImpl = SpringContextUtils.getBean("systemServiceImpl", SystemService.class);
						SSystemItemCustomLink sSystemItemCustomLink = null;
						try {
							sSystemItemCustomLink = systemServiceImpl.findOkOneByHostSiteSystemItemId(sPdtable.getHostId(), sPdtable.getSiteId(),
									sPdtable.getSystemId(), sPdtable.getId());
						} catch (IOException e) {
						}
						String href = siteUrlComponent.getPdtableHref(sPage, sCategories, sPdtable, sSystemItemCustomLink);
						value = "<a href=\"" + href + "\" >" + value + "</a>";
					}
					stringBuilder.append("<td>" + value + "</td>");
				}
			} else {
				stringBuilder.append("<td><!-- no value --></td>");
			}
		} else {
			stringBuilder.append("<td></td>");
		}
		return stringBuilder;
	}

	protected String tableTbodyTrHtml(SPage page, SCategories sCategories, List<SPdtableTitle> listSPdtableTitle, List<PdtableItem> rows,
			PdtableSysConfig pdtableSysConfig) {
		PdtableSysListTextConfig ltext = pdtableSysConfig.getLtext();
		String noData = ltext.getNoData();

		StringBuilder stringBuilder = new StringBuilder();
		if (CollUtil.isEmpty(rows)) {
			int colspan = listSPdtableTitle.size();
			stringBuilder.append("<tr><td colspan=\"" + colspan + "\">&nbsp;&nbsp;&nbsp;&nbsp;" + HtmlUtils.htmlEscape(noData) + "</td></tr>");
		} else {
			for (PdtableItem pdtableItem : rows) {
				stringBuilder.append("<tr>");
				for (SPdtableTitle sPdtableTitle : listSPdtableTitle) {
					StringBuilder tdTag = pdtableSystemItemHtml(page, sCategories, sPdtableTitle, pdtableItem, pdtableSysConfig);
					stringBuilder.append(tdTag);
				}
				stringBuilder.append("</tr>");
			}
		}

		return stringBuilder.toString();
	}

	protected String tableTheadTrThHtml(List<SPdtableTitle> listSPdtableTitle) {
		StringBuilder stringBuilder = new StringBuilder();

		for (SPdtableTitle sPdtableTitle : listSPdtableTitle) {
			Long id = sPdtableTitle.getId();
			String thTitle = sPdtableTitle.getTitle();
			String proportion = StrUtil.trim(sPdtableTitle.getProportion());
			String width = "";
			if (StrUtil.isNotBlank(proportion) && !proportion.equals("-1")) {
				width = "width=\"" + proportion + "%\"";
			}
			stringBuilder.append("<th class=\"\" " + width + " data-titleid=\"" + id + "\">" + HtmlUtils.htmlEscape(thTitle) + "</th>");
		}

		return stringBuilder.toString();
	}

	/**
	 * 制作搜索栏目
	 * 
	 * @param articleSysConfig
	 * @param keyword
	 * @param id
	 * @return
	 */
	protected StringBuilder search(PdtableSysConfig pdtableSysConfig, String keyword, String md5Id) {
		PdtableSysListConfig pdtableSysListConfig = pdtableSysConfig.getList();
		PdtableSysListTextConfig pdtableSysListTextConfig = pdtableSysConfig.getLtext();
		int showsearch = pdtableSysListConfig.getShowsearch();
		StringBuilder stringBuilder = new StringBuilder();
		if (showsearch == 0) {
			return stringBuilder;
		}

		String lanSearch = HtmlUtils.htmlEscape(pdtableSysListTextConfig.findLanSearch());
		String lanSearchInput = HtmlUtils.htmlEscape(pdtableSysListTextConfig.findLanSearchInput());
		String searchId = "search-" + md5Id;
		String inputId = "input-" + md5Id;
		if (StrUtil.isBlank(keyword)) {
			keyword = "";
		}

		stringBuilder = systemListSearch.render(searchId, inputId, lanSearch, lanSearchInput, keyword);
		return stringBuilder;
	}

	/**
	 * 制作面包屑
	 *
	 * @param downloadSysConfig
	 * @param page
	 * @param list
	 * @return
	 */
	protected String crumbs(PdtableSysConfig pdtableSysConfig, SPage page, List<SCategories> list) {
		PdtableSysListTextConfig ltext = pdtableSysConfig.getLtext();
		PdtableSysListConfig listPdtableSysListConfig = pdtableSysConfig.getList();
		int crumbslasttext = listPdtableSysListConfig.getCrumbslasttext();

		String yourCurrentLocation = HtmlUtils.htmlEscape(ltext.getYourCurrentLocation());
		StringBuilder stringBuilder = systemListCrumbs.render(yourCurrentLocation, crumbslasttext, page, list);

		return stringBuilder.toString();
	}

	/**
	 * 通过 categoryId 以及递归的方式获取 listSCategories 数据中全部的父级数据，然後加入到
	 * crumbsSCategoriesList 链表中
	 *
	 * @param crumbsSCategoriesList
	 * @param listSCategories
	 * @param categoryId
	 */
	protected static void idList(List<SCategories> crumbsSCategoriesList, List<SCategories> listSCategories, Long categoryId) {
		if (categoryId == null || categoryId.longValue() < 1) {
			return;
		}
		for (SCategories sCategories : listSCategories) {
			if (categoryId.longValue() == sCategories.getId().longValue()) {
				crumbsSCategoriesList.add(sCategories);
				if (sCategories.getParentId() != null && sCategories.getParentId().longValue() > 0) {
					idList(crumbsSCategoriesList, listSCategories, sCategories.getParentId());
				}
				break;
			}
		}
	}

	protected String pagewidthScript(String pagewidth) {
		StringBuilder stringBuilder = new StringBuilder();
		if (StrUtil.isBlank(pagewidth)) {
			return stringBuilder.toString();
		}
		Map<String, Object> mapData = new HashMap<>();
		mapData.put("pagewidth", pagewidth);
		StringWriter render = basicUdin.render(name, "pagewidth_script", mapData);
		stringBuilder.append(render);
		return stringBuilder.toString();
	}

	/**
	 * 通过左右、或者是上下结构确定顶部的class
	 * 
	 * @param productSysListConfig
	 * @return
	 */
	public static String getTopClass(PdtableSysListConfig pdtableSysListConfig) {
		int structure = pdtableSysListConfig.getStructure();
		if (structure == 2) {
			// 左右结构的时候
			return "side_left";
		}
		return "";
	}
}
